package com.zhentao.controller;

import com.zhentao.pojo.Nearby;
import com.zhentao.service.NearbyService;
import com.zhentao.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/nearby")
public class NearbyController {
    @Autowired
    private NearbyService nearbyService;
    public static final String SHOP_GEO_KEY = "shop:geo:";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void main() {
        List<Nearby> list = nearbyService.list();
        Map<Integer, List<Nearby>> map = list.stream().collect(Collectors.groupingBy(Nearby::getTypeId));
        for (Map.Entry<Integer, List<Nearby>> entry:map.entrySet()){
            Integer typeId = entry.getKey();
            String key=SHOP_GEO_KEY+typeId;
            List<Nearby> value = entry.getValue();
            List<RedisGeoCommands.GeoLocation<String>> locations=new ArrayList<>(value.size());
            for (Nearby nearby:value){
                locations.add(new RedisGeoCommands.GeoLocation<>(
                        nearby.getId().toString(),
                        new Point(nearby.getX(), nearby.getY())
                ));
            }
            stringRedisTemplate.opsForGeo().add(key, locations);
        }
    }
    @GetMapping("/of/type")
    public Result queryShopByType(
            @RequestParam("typeId") Integer typeId,
            @RequestParam(value = "current", defaultValue = "1") Integer current,
            @RequestParam(value = "x", required = false) Double x,
            @RequestParam(value = "y", required = false) Double y
    ){
        main();
        return nearbyService.queryShopByType(typeId, current, x, y);
    }
}
